package com.tedu.egweibo.controller;

import com.tedu.egweibo.common.result.JsonResult;
import com.tedu.egweibo.common.result.StatusCode;
import com.tedu.egweibo.mapper.UserMapper;
import com.tedu.egweibo.pojo.dto.UserLoginDTO;
import com.tedu.egweibo.pojo.dto.UserRegDTO;
import com.tedu.egweibo.pojo.entity.User;
import com.tedu.egweibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户注册功能")
    @PostMapping("/reg")
    public JsonResult Reg(@RequestBody @Validated UserRegDTO userRegDTO){
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        if (userMapper.selectByUserName(user.getUsername())==null){
            userMapper.insertUserRegDTO(user);
            return new JsonResult(StatusCode.OPERATION_SUCCESS);
        }
        return new JsonResult(StatusCode.USERNAME_EXIST);
    }

    @ApiOperation("用户登录功能")
    @PostMapping("/login")
    public JsonResult Login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        User user = userMapper.selectByUserName(userLoginDTO.getUsername());
        if (userLoginDTO.getUsername()==null||userLoginDTO.getUsername().isEmpty()){
            throw new RuntimeException("用户名不能为空");
        }
        if (user!=null){
            if (user.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",user);
                return new JsonResult(StatusCode.OPERATION_SUCCESS);
            }else {
                return new JsonResult(StatusCode.PASSWORD_ERROR);
            }
        }else {
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
    }

    @ApiOperation("查看当前用户信息")
    @GetMapping("/currentUser")
    public JsonResult currentUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user!=null){
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);
        }else {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
    }

    @ApiOperation("退出登录功能")
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }






}
